package com.hsgene.statistics.service.impl;

import com.hsgene.common.ClientType;
import com.hsgene.common.util.date.SimpleDateUtils;
import com.hsgene.common.util.redis.RedisConstants;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.common.util.support.Pagination;
import com.hsgene.order.dto.console.PostponeTestingOrderDto;
import com.hsgene.statistics.dto.HomeOrderStatisticsDto;
import com.hsgene.statistics.dto.HomeStatisticsDto;
import com.hsgene.statistics.dto.NewOrderStatisticsDto;
import com.hsgene.statistics.dto.OrderPostponeWarnDto;
import com.hsgene.statistics.persistence.AgencyStatisticsRepository;
import com.hsgene.statistics.persistence.ConsumablesStatisticsRepository;
import com.hsgene.statistics.persistence.OrderStatisticsRepository;
import com.hsgene.statistics.persistence.ProductStatisticsRepository;
import com.hsgene.statistics.service.StatisticsService;
import com.hsgene.statistics.service.api.OrderFeignService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 数据统计ServiceImpl
 *
 * @author wangbing
 * @version 1.0
 * @date 2018/12/20 16:13
 * Copyright: Copyright (c) 2018
 */
@Service
public class StatisticsServiceImpl implements StatisticsService {

    private final static String POSTPONE_WARN_USER_SET = RedisConstants.DEFAULT_REDIS_PREFIX + RedisConstants.COLON_SPLIT + "postpone_warn_user:";

    private final static Logger LOGGER = LoggerFactory.getLogger(StatisticsServiceImpl.class);

    @Resource
    private AgencyStatisticsRepository agencyStatisticsRepository;

    @Resource
    private ConsumablesStatisticsRepository consumablesStatisticsRepository;

    @Resource
    private OrderStatisticsRepository orderStatisticsRepository;

    @Resource
    private ProductStatisticsRepository productStatisticsRepository;

    @Resource
    private OrderFeignService orderFeignService;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public ApiResult<HomeStatisticsDto> getHomeStatistics(String userId) {
        HomeStatisticsDto statistics = new HomeStatisticsDto();
        statistics.setPackageCount(productStatisticsRepository.queryAvailablePackageCount());
        statistics.setAgencyCount(agencyStatisticsRepository.queryAvailableAgencyCount());
        statistics.setGoodsAuditCount(consumablesStatisticsRepository.queryGoodsAuditCount());
        HomeOrderStatisticsDto orderStatistics = new HomeOrderStatisticsDto();
        orderStatistics.setPendingCount(orderStatisticsRepository.queryPendingCount());
        orderStatistics.setAgencyPendingCount(orderStatisticsRepository.queryAgencyPendingCount());
        Date now = new Date();
        List<NewOrderStatisticsDto> countList = orderStatisticsRepository.queryNewCount(SimpleDateUtils.getDateOfMidNight(now), SimpleDateUtils.getDateOfTodayEnd(now));
        if (!CollectionUtils.isEmpty(countList)) {
            countList.forEach(e -> {
                orderStatistics.setNewCount(orderStatistics.getNewCount() + e.getCount());
                if (e.getOrigin().equals(ClientType.PEANUT.getCode())) {
                    orderStatistics.setNewPeanutCount(orderStatistics.getNewPeanutCount() + e.getCount());
                } else if (e.getOrigin().equals(ClientType.GOLD_COLORED_GLASS.getCode())) {
                    orderStatistics.setNewDoctorCount(orderStatistics.getNewDoctorCount() + e.getCount());
                } else {
                    orderStatistics.setNewCustomerCount(orderStatistics.getNewCustomerCount() + e.getCount());
                }
            });
        }
        statistics.setOrderStatistics(orderStatistics);
        OrderPostponeWarnDto postponeWarn = orderStatisticsRepository.queryPostponeWarn();
        if (userId != null) {
            postponeWarn.setPostponeWarn(getPostponeWarn(userId));
        }
        statistics.setPostponeWarnInfo(postponeWarn);
        ApiResult<Pagination<PostponeTestingOrderDto>> orderResult = orderFeignService.queryOrders(7,1,"postpone");
        if (orderResult.isSucc()) {
            statistics.setPostponeOrders(orderResult.getData().getResult());
        } else {
            LOGGER.error("查询超期检测订单失败：" + orderResult.getDesc());
        }

        return ApiResult.succ(statistics);
    }

    /**
     * 获取超期检测提醒标志位
     *
     * @param userId 用户id
     * @return 超期检测提醒标志位（0：不提示；1：提示超期）
     */
    private Integer getPostponeWarn(String userId) {
        String today = SimpleDateUtils.formatDate(new Date(), SimpleDateUtils.DatePattern.YYYY_MM_DD);
        String redisKey = POSTPONE_WARN_USER_SET + today;
        boolean isMember = Boolean.TRUE.equals(redisTemplate.opsForSet().isMember(redisKey, userId));
        if (!isMember) {
            boolean hasKey = Boolean.TRUE.equals(redisTemplate.hasKey(redisKey));
            redisTemplate.opsForSet().add(redisKey, userId);
            if (!hasKey) {
                redisTemplate.expire(redisKey, 1L, TimeUnit.DAYS);
            }
        }
        return isMember ? 0 : 1;
    }
}
